<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
class Wx extends Controller{
    public $appid;
    public $secret;
    public function __construct(){
        parent::__construct();
        $this->appid = config('wx_appid');
        $this->secret = config('wx_appsecret');
    }


    /**
     * 获取access_token
     */
    public function get_access_token(){
        if($access_token = cache('access_token')){
            return $access_token;
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}";
            $info = file_get_contents($url);
            $info = json_decode($info,true);
            $access_token = $info['access_token'];

            cache('access_token',$access_token,7100);

            return $access_token;
        }
    }

    /**
     * 获取openid
     */
    public function get_openid($code){
        //通过code换取网页授权access_token
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->secret}&code={$code}&grant_type=authorization_code";
        $info = file_get_contents($url);
        $info = json_decode($info,true);
        //根据openid获取用户详细信息
        $url= "https://api.weixin.qq.com/sns/userinfo?access_token={$info['access_token']}&openid={$info['openid']}&lang=zh_CN";
        $res = file_get_contents($url);
        $res = json_decode($res,true);
        return  $res;



    }


    public function aa(){
        $arr = [
            'aa' => ''
        ];
        return $arr;
    }

}
